package com.sbw.springboot.demo.config;

import com.sbw.springboot.demo.statemachine.RegEventEnum;
import com.sbw.springboot.demo.statemachine.RegStatusEnum;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.EnumStateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;

import java.util.EnumSet;

/**
 * @Author: sangbowei
 * @Description: 状态机配置
 * @Date: Created in  20:28 2017\12\23 0023
 **/
@Configuration
@EnableStateMachine
public class StateMachineConfig extends EnumStateMachineConfigurerAdapter<RegStatusEnum, RegEventEnum> {

    @Override
    public void configure(StateMachineStateConfigurer<RegStatusEnum, RegEventEnum> states) throws Exception {
        states.withStates()
                //  定义了初始状态是未连接状态
                .initial(RegStatusEnum.UNCONNECTED)
                //  定义了定义状态机中存在的所有状态
                .states(EnumSet.allOf(RegStatusEnum.class));
    }

    /**
     * 以连接事件为案例，其中 source 指定原始状态，target 指定目标状态，event 指定触发事件
     * @param transitions
     * @throws Exception
     */
    @Override
    public void configure(StateMachineTransitionConfigurer<RegStatusEnum, RegEventEnum> transitions)
            throws Exception {
        transitions
                // 1.连接事件
                // 未连接 -> 已连接
                .withExternal()
                .source(RegStatusEnum.UNCONNECTED)
                .target(RegStatusEnum.CONNECTED)
                .event(RegEventEnum.CONNECT)
                .and()

                // 2.注册事件
                // 已连接 -> 注册中
                .withExternal()
                .source(RegStatusEnum.CONNECTED)
                .target(RegStatusEnum.REGISTERING)
                .event(RegEventEnum.REGISTER)
                .and()

                // 3.注册成功事件
                // 注册中 -> 已注册
                .withExternal()
                .source(RegStatusEnum.REGISTERING)
                .target(RegStatusEnum.REGISTERED)
                .event(RegEventEnum.REGISTER_SUCCESS)
                .and()

                // 5.注销事件
                // 已连接 -> 未连接
                .withExternal()
                .source(RegStatusEnum.CONNECTED)
                .target(RegStatusEnum.UNCONNECTED)
                .event(RegEventEnum.UN_REGISTER)
                .and()
                // 注册中 -> 未连接
                .withExternal()
                .source(RegStatusEnum.REGISTERING)
                .target(RegStatusEnum.UNCONNECTED)
                .event(RegEventEnum.UN_REGISTER)
                .and()
                // 已注册 -> 未连接
                .withExternal()
                .source(RegStatusEnum.REGISTERED)
                .target(RegStatusEnum.UNCONNECTED)
                .event(RegEventEnum.UN_REGISTER)
        ;
    }
}